<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
        <title>博客后台管理 - 写文章</title>
        <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-touch-fullscreen" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="default">
        <link rel="stylesheet" type="text/css" href="css/materialdesignicons.min.css">
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/style.min.css">
        <link rel="stylesheet" href="./elementui/index.min.css">
        <link rel="stylesheet" href="./tuieditor/toastui-editor.min.css">
        <style>
            /* v-cloak 隐藏未渲染的DOM */
            [v-cloak] {
                display: none;
            }
        </style>
        <style>
            .elform-editor .el-form-item__content {
                margin-left: 0 !important;
            }
        </style>

    </head>

    <body>
        <div id="app">

            <el-row style="padding: 15px;">
                <el-form ref="articleForm" :model="articleForm" :rules="articleFormRules" label-width="80px">
                    <!-- 文章标题 -->
                    <el-form-item label="文章标题" prop="title">
                        <el-input v-model="articleForm.title" clearable></el-input>
                    </el-form-item>
                    <!-- 文章分类 -->
                    <el-form-item label="文章分类" prop="cate_name">
                        <el-select v-model="articleForm.cate_name" clearable placeholder="请选择分类">
                            <el-option v-for="cate in cateList" :key="cate.id" :label="cate.name" :value="cate.name">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- 文章描述 -->
                    <el-form-item label="文章描述" prop="description">
                        <el-input type="textarea" :rows="2" v-model="articleForm.description" clearable></el-input>
                    </el-form-item>
                    <!-- 是否置顶 -->
                    <el-form-item label="是否置顶" prop="istop">
                        <el-switch v-model="articleForm.istop" :active-value="1" :inactive-value="0"></el-switch>
                    </el-form-item>
                    <!-- 文章内容 -->
                    <el-form-item class="elform-editor" :label-width="0">
                        <div id="editor"></div>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" size="small" @click="publishArticle()">发布</el-button>
                        <el-button size="small" @click="resetForm()">重置</el-button>
                    </el-form-item>
                </el-form>

            </el-row>


        </div>

        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="js/popper.min.js"></script>
        <script type="text/javascript" src="js/bootstrap.min.js"></script>
        <script type="text/javascript" src="js/main.min.js"></script>
        <script src="./elementui/vue.min.js"></script>
        <script src="./elementui/index.min.js"></script>
        <script src="./tuieditor/toastui-editor-all.min.js"></script>
        <script>
            const Editor = toastui.Editor;
            var editor = undefined; // markdown编辑器实例

            new Vue({
                el: '#app',
                data: {
                    // 分类列表
                    cateList: [],
                    // 添加文章表单
                    articleForm: {
                        title: '',
                        cate_name: '',
                        description: '',
                        content: '',
                        istop: 0,
                        created_at: '',
                        updated_at: '',
                    },
                    // 添加文章表单验证规则
                    articleFormRules: {
                        title: [
                            { required: true, message: '请输入文章标题', trigger: 'blur' },
                        ],
                        cate_name: [
                            { required: true, message: '请选择分类', trigger: 'change' }
                        ],
                        description: [
                            { required: true, message: '请输入文章描述', trigger: 'blur' }
                        ],
                    },
                    // 文章id，用于编辑文章，为0表示添加文章
                    articleId: 0,
                    // 编辑器是否全屏
                    editorIsFullscreen: false,
                },
                methods: {
                    // 发布文章
                    publishArticle() {
                        // 表单验证
                        this.$refs.articleForm.validate(valid => {
                            if (!valid) {   // 表单验证不通过
                                return this.$message.warning('请检查表单是否填写完整！');
                            }

                            if (editor.getMarkdown() == '') {
                                return this.$message.warning('文章内容不能为空！');
                            }
                            this.articleForm.content = editor.getHtml();

                            if (this.articleId == 0) {  // 添加文章
                                this.articleForm.created_at = getNowTimeStr();
                                this.articleForm.updated_at = getNowTimeStr();

                                fetch("http://127.0.0.1:5588/admin/articles", {
                                    method: "POST",
                                    headers: {
                                        "Content-Type": "application/json;charset=UTF-8",
                                        "Authorization": sessionStorage.getItem('token') || '',
                                    },
                                    body: JSON.stringify(this.articleForm),
                                })
                                    .then((response) => response.json())
                                    .then(res => {
                                        if (res.code != 200) {
                                            return this.$message.error(res.msg);
                                        }

                                        this.$message.success('操作成功！');
                                        this.resetForm();
                                    })
                                    .catch((err) => {
                                        console.error("Error:", err);
                                    });

                            } else {    // 编辑文章
                                let formData = {
                                    id: this.articleId,
                                    updated_at: getNowTimeStr(),
                                    ...this.articleForm
                                };

                                fetch("http://127.0.0.1:5588/admin/articles/", {
                                    method: "PUT",
                                    headers: {
                                        "Content-Type": "application/json;charset=UTF-8",
                                        "Authorization": sessionStorage.getItem('token') || '',
                                    },
                                    body: JSON.stringify(formData),
                                })
                                    .then((response) => response.json())
                                    .then(res => {
                                        if (res.code != 200) {
                                            return this.$message.error(res.msg);
                                        }

                                        this.$message.success('操作成功！');
                                        this.resetForm();
                                    })
                                    .catch((err) => {
                                        console.error("Error:", err);
                                    })

                            }
                        });
                    },
                    // 重置表单
                    resetForm() {
                        this.$refs.articleForm.resetFields();
                        // 清空编辑器内容
                        editor.setHTML('');
                        editor.setMarkdown('');
                    },
                },
                mounted() {
                    // 获取URL中的article id参数
                    const params = new URL(window.location.href)
                    const searchParams = params.searchParams
                    const aid = searchParams.get('aid') || '';


                    // 获取分类列表
                    fetch("http://127.0.0.1:5588/admin/categories", {
                        method: "GET",
                        headers: {
                            "Authorization": sessionStorage.getItem('token') || '',
                        },
                    })
                        .then((response) => response.json())
                        .then(res => {
                            if (res.code != 200) {
                                return this.$message.error(res.msg);
                            }

                            this.cateList = res.data;
                        })
                        .catch((err) => {
                            console.error("Error:", err);
                        });

                    // 创建编辑器
                    editor = new Editor({
                        el: document.querySelector('#editor'),
                        height: '500px',
                        language: 'zh-CN',  // 设置语言为中文
                        initialEditType: 'markdown',    // 设置编辑器初始模式为Markdown
                        previewStyle: 'vertical',   // 设置预览样式为垂直
                        usageStatistics: false, // 禁用统计数据
                        previewHighlight: true, // 启用高亮
                    });



                    // 获取文章详情,并填充到表单中
                    if (aid != '') {
                        fetch(`http://127.0.0.1:5588/api/article/${aid}`, {
                            method: "GET",
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.articleForm = res.data;    // 将数据填充到表单中
                                this.articleId = res.data.id;   // 记录文章id
                                // 设置文章内容
                                editor.setHTML(res.data.content);
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    }
                }
            });

            // 获取当前时间字符串
            function getNowTimeStr() {
                let now = new Date();
                let year = now.getFullYear();
                let month = now.getMonth() + 1;
                let day = now.getDate();
                let hour = now.getHours();
                let minute = now.getMinutes();
                let second = now.getSeconds();

                let datetimeStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                return datetimeStr;
            }
        </script>
    </body>

</html>